using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using  DeloitteForms = Deloitte.Windows;
using Deloitte.Data;
using Deloitte.Common;
using Deloitte.Windows.Controls;

namespace Deloitte.Windows.Forms
{
	/// <summary>
	/// Summary description for FormDataGrid.
	/// </summary>
	public class DataGridViewForm : System.Windows.Forms.Form
	{
		#region "Control Declarations"
		private DeloitteForms.Controls.DataViewSortControl  ctlDV=null;
		private DeloitteForms.Controls.DataViewRowFilterControl ctlDVFilter=null;
		private DeloitteForms.Controls.ExcelExportControl ctlExcelExport=null;
		private DeloitteForms.Controls.DistinctColumnValuesControl ctlSelectDistinct=null;
#endregion						
        private DataView myView;
        private DataTable2 myDataTable;
        private Control ctlOptions;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem miSort;
		private System.Windows.Forms.MenuItem miOptions;
		private System.Windows.Forms.MenuItem miOptionsClear;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem miExcelExport;
		private System.Windows.Forms.MenuItem miFilter;
        private System.Windows.Forms.MenuItem menuItem2;
        private System.Windows.Forms.ToolTip toolTip1;
		private System.Windows.Forms.MenuItem menuItem4;
        private System.Windows.Forms.MenuItem mdiHideShowCols;
        private System.Windows.Forms.MenuItem miSelectDistinct;
        private BackgroundWorker backgroundWorker1;
        public DataGridView dataGridView1;
        private SplitContainer splitContainer1;
        private TextBox filterText;
        private ComboBox cboColumnNames;
        private ErrorProvider errorProvider1;
        private Button btnOK;
        private Button btnCancel;
        private Button button1;
        private MenuItem menuItem3;
        private MenuItem miOpen;
        private MenuItem menuItem6;
        private OpenFileDialog openFileDialog1;
        private ComboBox cboTables;        
		private System.ComponentModel.IContainer components;

		public DataGridViewForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();	
			this.CommonConstructorCode();
			
		}
		
		public DataGridViewForm(DataTable2 aDataTable, bool isDGReadOnly)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			try
			{
				this.CommonConstructorCode();
				this.CurrentDataTable = aDataTable;				
				this.dataGridView1.ReadOnly=isDGReadOnly;			
			}
			catch (Exception ex){throw new Exception(ex.ToString());}
		}
        public DataGridViewForm(DataTable aDataTable, bool isDGReadOnly)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			try
			{                
				this.CommonConstructorCode();
				this.CurrentDataTable = new DataTable2(aDataTable);				
				this.dataGridView1.ReadOnly=isDGReadOnly;			
			}
			catch (Exception ex){throw new Exception(ex.ToString());}
		}
		public DataTable2 CurrentDataTable
		{
			get{return this.myDataTable;}
			set
			{
				this.myDataTable = value;
				this.myView = this.myDataTable.DefaultView;                
                this.dataGridView1.DataSource = this.myView;
                this.SetColumnNameComboBox();
			}
		}
        private void SetColumnNameComboBox()
        {
            this.cboColumnNames.Items.Clear();
            foreach (DataColumn dc in this.myDataTable.Columns) { this.cboColumnNames.Items.Add(dc.ColumnName); }
        }
		private void CommonConstructorCode()
		{
			this.SetDataGridEvents();							
			this.splitContainer1.Panel2.ControlAdded +=new ControlEventHandler(panelOptions_ControlAdded);
			this.splitContainer1.Panel2.ControlRemoved +=new ControlEventHandler(panelOptions_ControlRemoved);
			//this.panelOKCancel.Controls.Add(new DeloitteForms.Controls.ControlOKCancel(this));			
		}
		private void SetOptionsPanel()
		{	
			this.splitContainer1.Panel2.Controls.Clear();			
			this.splitContainer1.Panel2.Controls.Add(ctlOptions);
			this.ctlOptions.Size = this.splitContainer1.Panel2.Size;
			this.ctlOptions.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));		
		}
		private void SetDataGridEvents()
		{
			try
			{							
				dataGridView1.DataSourceChanged += new EventHandler(dataGridView1_DataSourceChanged);
				this.Resize += new EventHandler(FormDataGrid_Resize);
			}
			catch{}
		}
		private void dataGridView1_DataSourceChanged(object sender, EventArgs e)
		{
            
            //try
            //{
            //    if(this.dataGridView1.DataSource != null)
            //    {					
            //        if(this.dataGridView1.DataSource.GetType().Name == "DataView")
            //        {
            //            this.myView = (DataView) this.dataGridView1.DataSource;
            //            Utility.AutoFormatDataGridViewColumns(myView.Table, this.dataGridView1, this.dataGridView1.ReadOnly);
            //        }
            //        else if (this.dataGridView1.DataSource.GetType().Name == "DataTable" || this.dataGridView1.DataSource.GetType().Name == "DataTable2")
            //        {
            //            this.myView = ((DataTable) this.dataGridView1.DataSource).DefaultView;
            //            Utility.AutoFormatDataGridViewColumns(myView.Table, this.dataGridView1, this.dataGridView1.ReadOnly);
            //        }
            //    }
            //}
            //catch (Exception ex){throw new Exception(ex.ToString());}
		}

		public bool IsDataGridReadOnly
		{
			get{return this.dataGridView1.ReadOnly;}
			set{this.dataGridView1.ReadOnly = value;}
		}
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.miOpen = new System.Windows.Forms.MenuItem();
            this.menuItem6 = new System.Windows.Forms.MenuItem();
            this.miOptions = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.miExcelExport = new System.Windows.Forms.MenuItem();
            this.miFilter = new System.Windows.Forms.MenuItem();
            this.miSort = new System.Windows.Forms.MenuItem();
            this.miSelectDistinct = new System.Windows.Forms.MenuItem();
            this.miOptionsClear = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.mdiHideShowCols = new System.Windows.Forms.MenuItem();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.filterText = new System.Windows.Forms.TextBox();
            this.cboColumnNames = new System.Windows.Forms.ComboBox();
            this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
            this.btnOK = new System.Windows.Forms.Button();
            this.btnCancel = new System.Windows.Forms.Button();
            this.button1 = new System.Windows.Forms.Button();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.cboTables = new System.Windows.Forms.ComboBox();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit();
            this.SuspendLayout();
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem3,
            this.miOptions,
            this.menuItem2});
            // 
            // menuItem3
            // 
            this.menuItem3.Index = 0;
            this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.miOpen,
            this.menuItem6});
            this.menuItem3.Text = "&File";
            // 
            // miOpen
            // 
            this.miOpen.Index = 0;
            this.miOpen.Text = "&Open";
            this.miOpen.Click += new System.EventHandler(this.miOpen_Click);
            // 
            // menuItem6
            // 
            this.menuItem6.Index = 1;
            this.menuItem6.Text = "Save &As";
            // 
            // miOptions
            // 
            this.miOptions.Index = 1;
            this.miOptions.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem1,
            this.miFilter,
            this.miSort,
            this.miSelectDistinct,
            this.miOptionsClear});
            this.miOptions.Text = "&Tools";
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 0;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.miExcelExport});
            this.menuItem1.Text = "&Export";
            // 
            // miExcelExport
            // 
            this.miExcelExport.Index = 0;
            this.miExcelExport.Text = "E&xcel";
            this.miExcelExport.Click += new System.EventHandler(this.miExcelExport_Click);
            // 
            // miFilter
            // 
            this.miFilter.Index = 1;
            this.miFilter.Text = "&Filter";
            this.miFilter.Click += new System.EventHandler(this.miFilter_Click);
            // 
            // miSort
            // 
            this.miSort.Index = 2;
            this.miSort.Text = "&Sort";
            this.miSort.Click += new System.EventHandler(this.miSort_Click);
            // 
            // miSelectDistinct
            // 
            this.miSelectDistinct.Index = 3;
            this.miSelectDistinct.Text = "Select &Distinct";
            this.miSelectDistinct.Click += new System.EventHandler(this.miSelectDistinct_Click);
            // 
            // miOptionsClear
            // 
            this.miOptionsClear.Index = 4;
            this.miOptionsClear.Text = "&Clear";
            this.miOptionsClear.Click += new System.EventHandler(this.miOptionsClear_Click);
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 2;
            this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.menuItem4});
            this.menuItem2.Text = "&View";
            // 
            // menuItem4
            // 
            this.menuItem4.Index = 0;
            this.menuItem4.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
            this.mdiHideShowCols});
            this.menuItem4.Text = "&Columns";
            // 
            // mdiHideShowCols
            // 
            this.mdiHideShowCols.Index = 0;
            this.mdiHideShowCols.Text = "Hide/Show Columns";
            this.mdiHideShowCols.Click += new System.EventHandler(this.mdiHideShowCols_Click);
            // 
            // backgroundWorker1
            // 
            this.backgroundWorker1.WorkerSupportsCancellation = true;
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToOrderColumns = true;
            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCellsExceptHeader;
            this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.ControlLightLight;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dataGridView1.Location = new System.Drawing.Point(0, 0);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(740, 373);
            this.dataGridView1.TabIndex = 3;
            // 
            // splitContainer1
            // 
            this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.splitContainer1.Location = new System.Drawing.Point(16, 35);
            this.splitContainer1.Name = "splitContainer1";
            this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
            // 
            // splitContainer1.Panel1
            // 
            this.splitContainer1.Panel1.Controls.Add(this.dataGridView1);
            // 
            // splitContainer1.Panel2
            // 
            this.splitContainer1.Panel2.BackColor = System.Drawing.SystemColors.ControlLightLight;
            this.splitContainer1.Size = new System.Drawing.Size(740, 464);
            this.splitContainer1.SplitterDistance = 373;
            this.splitContainer1.SplitterWidth = 6;
            this.splitContainer1.TabIndex = 4;
            // 
            // filterText
            // 
            this.filterText.Location = new System.Drawing.Point(262, 8);
            this.filterText.Name = "filterText";
            this.filterText.Size = new System.Drawing.Size(226, 21);
            this.filterText.TabIndex = 5;
            this.filterText.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
            // 
            // cboColumnNames
            // 
            this.cboColumnNames.FormattingEnabled = true;
            this.cboColumnNames.Location = new System.Drawing.Point(118, 8);
            this.cboColumnNames.Name = "cboColumnNames";
            this.cboColumnNames.Size = new System.Drawing.Size(142, 21);
            this.cboColumnNames.TabIndex = 6;
            // 
            // errorProvider1
            // 
            this.errorProvider1.ContainerControl = this;
            // 
            // btnOK
            // 
            this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.btnOK.Location = new System.Drawing.Point(12, 8);
            this.btnOK.Name = "btnOK";
            this.btnOK.Size = new System.Drawing.Size(37, 21);
            this.btnOK.TabIndex = 7;
            this.btnOK.Text = "&OK";
            this.btnOK.UseVisualStyleBackColor = true;
            // 
            // btnCancel
            // 
            this.btnCancel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.btnCancel.Location = new System.Drawing.Point(55, 8);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(57, 21);
            this.btnCancel.TabIndex = 7;
            this.btnCancel.Text = "&Cancel";
            this.btnCancel.UseVisualStyleBackColor = true;
            // 
            // button1
            // 
            this.button1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
            this.button1.Location = new System.Drawing.Point(523, 7);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(57, 21);
            this.button1.TabIndex = 7;
            this.button1.Text = "Test";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // openFileDialog1
            // 
            this.openFileDialog1.FileName = "openFileDialog1";
            // 
            // cboTables
            // 
            this.cboTables.FormattingEnabled = true;
            this.cboTables.Location = new System.Drawing.Point(586, 7);
            this.cboTables.Name = "cboTables";
            this.cboTables.Size = new System.Drawing.Size(142, 21);
            this.cboTables.TabIndex = 8;
            // 
            // FormDataGridView
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(768, 531);
            this.Controls.Add(this.cboTables);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.btnCancel);
            this.Controls.Add(this.btnOK);
            this.Controls.Add(this.cboColumnNames);
            this.Controls.Add(this.filterText);
            this.Controls.Add(this.splitContainer1);
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Menu = this.mainMenu1;
            this.Name = "FormDataGridView";
            this.Text = "Data Grid View Form";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		private void lnkOK_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			this.DialogResult= DialogResult.OK;
		}

		private void lnkCancel_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			this.DialogResult= DialogResult.Cancel;
		}

		private void FormDataGrid_Resize(object sender, EventArgs e)
		{
			if(this.ctlOptions!=null)this.ctlOptions.Size =this.splitContainer1.Panel2.Size;			
		}

		private void miSort_Click(object sender, System.EventArgs e)
		{
			if(this.ctlDV ==null) this.ctlDV = new DataViewSortControl(this.myView);
			this.ctlOptions  = this.ctlDV;
			this.SetOptionsPanel();
		}

		private void panelOptions_ControlAdded(object sender, ControlEventArgs e)
		{
			if(this.dataGridView1.Size.Height==this.splitContainer1.Panel1.Size.Height)this.dataGridView1.Size= new Size(this.splitContainer1.Size.Width, (int)(this.splitContainer1.Size.Height * .75));
//			if (isGridExpanded)
//			{				
//				this.dataGridView1.Size = new Size(this.dataGridView1.Size.Width,(this.dataGridView1.Size.Height - this.panelOptions.Size.Height));
//				this.panelOptions.Visible=true;
//				isGridExpanded = false;				
//			}
		}

		private void panelOptions_ControlRemoved(object sender, ControlEventArgs e)
		{
//			this.dataGridView1.Size = new Size(this.panel1.Size.Width, this.panel1.Size.Height);
//			if(!isGridExpanded)
//			{
//				this.dataGridView1.Size = new Size(this.dataGridView1.Size.Width,(this.dataGridView1.Size.Height + this.panelOptions.Size.Height));
//				this.panelOptions.Visible=false;
//				isGridExpanded = true;
//			}
			}

		private void miOptionsClear_Click(object sender, System.EventArgs e)
		{
			this.splitContainer1.Panel2.Controls.Clear();
			this.splitContainer1.Panel1.Size = new Size(this.splitContainer1.Size.Width, this.splitContainer1.Size.Height);
		}

		private void miExcelExport_Click(object sender, System.EventArgs e)
		{
			try
			{
                ///export what is displayed in the grid
				if(this.ctlExcelExport ==null) this.ctlExcelExport = new Deloitte.Windows.Controls.ExcelExportControl(Utility.CreateDataTable(this.dataGridView1));
				this.ctlOptions  = this.ctlExcelExport;                
				this.SetOptionsPanel();
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}

		private void miFilter_Click(object sender, System.EventArgs e)
		{
			try
			{
				if(this.ctlDVFilter ==null) this.ctlDVFilter = new DeloitteForms.Controls.DataViewRowFilterControl(this.myView);
				this.ctlOptions  = this.ctlDVFilter;
				this.SetOptionsPanel();
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}

		private void miViewDeletedRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.Deleted;
		}

		private void miViewCurrentRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.Deleted;
		}

		private void miModifiedCurrRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.ModifiedCurrent;
		}

		private void miModifiedOriginalRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.ModifiedOriginal;
		}

		private void miOriginalRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.OriginalRows;
		}

		private void miUnchangedRows_Click(object sender, System.EventArgs e)
		{
			this.myView.RowStateFilter = System.Data.DataViewRowState.Unchanged;
		}

		private void mdiHideShowCols_Click(object sender, System.EventArgs e)
		{
			
		}

		private void miSelectDistinct_Click(object sender, System.EventArgs e)
		{
			try
			{
				if(this.ctlSelectDistinct ==null) this.ctlSelectDistinct = new DeloitteForms.Controls.DistinctColumnValuesControl(this.CurrentDataTable);
				this.ctlOptions  = this.ctlSelectDistinct;
				this.SetOptionsPanel();
			}
			catch(Exception ex){throw new Exception(ex.ToString());}
		}

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

            try
            {
                if (this.myDataTable.Columns[this.cboColumnNames.Text].DataType == typeof(string))
                {
                    this.myView.RowFilter = "[" + this.cboColumnNames.Text + "] LIKE '%" + this.filterText.Text + "%'";
                }
            }
            catch { this.errorProvider1.SetError(this.filterText, "Invalid Filter"); }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable2 dt = new DataTable2(Utility.CreateDataTable(this.dataGridView1));
            dt.ShowInDataForm();
        }

        private void miOpen_Click(object sender, EventArgs e)
        {
            OpenDataFile();
        }
        private void OpenDataFile()
        {
            try
            {
                if (this.openFileDialog1 == null) this.openFileDialog1 = new OpenFileDialog();
                this.openFileDialog1.Title = @"Open Data Source";
                this.openFileDialog1.Filter = @"XML File (*.xml)|*.xml";
                //todo: add a filter on the dialog for excel files and ODBC Data sources
                if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
                {                                 
                    this.CurrentDataTable = new DataTable2(Utility.LoadXMLFileToDataSet(this.openFileDialog1.FileName).Tables[0]); ;
                }                
            }
            catch (Exception ex) { ExceptionHandling.ShowMessageBox(ex); }
        }

	}
}
